package com.ltmonitor.web.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
import javax.servlet.http.HttpServletRequest;

import com.ltmonitor.entity.AlarmRecord;
import com.ltmonitor.web.util.JsonMessage;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ltmonitor.entity.AlarmConfig;
import com.ltmonitor.entity.Department;
import com.ltmonitor.service.IAlarmConfigService;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 配置报警类型是否启用，报警声音是否启用。
 * 
 * @author Administrator
 * 
 */

@Controller
@RequestMapping("/alarmConfig")
public class AlarmConfigAction extends GenericAction {

	@Autowired
	private IAlarmConfigService alarmConfigService;

	@RequestMapping("/view")
	public String view(Model m) {
		Collection<AlarmConfig> alarmConfigs = alarmConfigService.loadAll();

		for (Object obj : alarmConfigs) {
			AlarmConfig a = (AlarmConfig) obj;
			String sourceDescr = super.convert(a.getAlarmSource(),
					"AlarmSource");
			a.setAlarmSource(sourceDescr);
		}
		m.addAttribute("alarmConfigs", alarmConfigs);
		return "/alarm/alarmConfig";

	}
	@RequestMapping("/viewAlarmConfigByDepId")
	public String viewAlarmConfigByDepId(long depId, Model m) {
		Collection<AlarmConfig> alarmConfigs = alarmConfigService.getAlarmConfigByDepId(depId);
		boolean  isNew = false;
		if(depId > 0 && alarmConfigs.size() == 0)
		{
			isNew = true;
			long defaultId = 0;
			alarmConfigs = alarmConfigService.getAlarmConfigByDepId(defaultId); //获取系统默认的报警配置
		}

		for (AlarmConfig a  : alarmConfigs) {
			String sourceDescr = super.convert(a.getAlarmSource(),
					"AlarmSource");
			a.setAlarmSource(sourceDescr);
		}

		Department d = this.departmentService.load(depId);
		if(d != null)
		{
			m.addAttribute("depName", d.getName());
		}
		m.addAttribute("alarmConfigs", alarmConfigs);
		m.addAttribute("depId", depId);
		m.addAttribute("isNew", isNew);
		return "/alarm/alarmConfig";

	}

	@RequestMapping("/deleteByDep")
	public String deleteByDep(long depId, Model m)
	{
		if(depId > 0)
		{
			this.alarmConfigService.deleteAlarmConfigByDepId(depId);
		}
		return viewAlarmConfigByDepId(depId,m);
	}

	/**
	 * 报警参数设置
	 * @param alarmEnable
	 * @param alarmSoundEnable
	 * @param alarmPopupEnable
	 *            是否弹窗
	 * @param alarmStatisticEnable
	 *            是否启动报警统计
	 * @param m
	 * @return
	 */
	@RequestMapping("/config")
	public String config(long depId, long[] alarmEnable, long[] alarmSoundEnable,
			long[] alarmPopupEnable, long[] alarmStatisticEnable, boolean isNew, Model m) {
		try {
			Collection<AlarmConfig> alarmConfigs = null;
			if(isNew)
			   alarmConfigs = alarmConfigService.getAlarmConfigByDepId(0);
			else
			   alarmConfigs = alarmConfigService.getAlarmConfigByDepId(depId);
			   
			// alarmTypes =
			// AlarmConfigService.getAlarmConfigByParentCode("AlarmType");
			HashMap<Long, Long> alarmEnableMap = new HashMap<Long, Long>();
			HashMap<Long, Long> soundEnableMap = new HashMap<Long, Long>();
			HashMap<Long, Long> popupEnableMap = new HashMap<Long, Long>();
			HashMap<Long, Long> statisticEnableMap = new HashMap<Long, Long>();
			if (alarmEnable != null) {
				for (long typeId : alarmEnable) {
					alarmEnableMap.put(typeId, typeId);
				}
			}
			if (alarmSoundEnable != null) {
				for (long typeId : alarmSoundEnable) {
					soundEnableMap.put(typeId, typeId);
				}
			}
			if (alarmPopupEnable != null) {
				for (long typeId : alarmPopupEnable) {
					popupEnableMap.put(typeId, typeId);
				}
			}

			if (alarmStatisticEnable != null) {
				for (long typeId : alarmStatisticEnable) {
					statisticEnableMap.put(typeId, typeId);
				}
			}

			for (AlarmConfig a : alarmConfigs) {
				long typeId = a.getEntityId();
				a.setEnabled(alarmEnableMap.containsKey(typeId));
				a.setSoundEnabled(soundEnableMap.containsKey(typeId));
				a.setPopupEnabled(popupEnableMap.containsKey(typeId));
				a.setStatisticEnabled(statisticEnableMap.containsKey(typeId));
				a.setDepId(depId);
				if(isNew)
				{
					a.setEntityId(0);
				}
			}
			this.alarmConfigService.saveOrUpdateAll(alarmConfigs);
			for (Object obj : alarmConfigs) {
				AlarmConfig a = (AlarmConfig) obj;
				String sourceDescr = super.convert(a.getAlarmSource(),
						"AlarmSource");
				a.setAlarmSource(sourceDescr);
			}

			m.addAttribute("depId", depId);
			m.addAttribute("isNew", false);
			m.addAttribute("message", "保存成功");
			m.addAttribute("alarmConfigs", alarmConfigs);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			m.addAttribute("message", ex.getMessage());
		}
		return "/alarm/alarmConfig";
	}

	@RequestMapping("/saveConfig")
	public String saveConfig(AlarmConfig ac, Model m) {
		try {
			//AlarmConfig ac = (AlarmConfig) super.populateEntity();
			/**
			ac.setEnabled(alarmEnable != null);
			ac.setSoundEnabled(alarmSoundEnable != null);
			ac.setPopupEnabled(alarmPopupEnable != null);
			ac.setStatisticEnabled(alarmStatisticEnable != null);*/
			this.alarmConfigService.saveOrUpdate(ac);

			m.addAttribute("message", "保存成功");
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			m.addAttribute("message", ex.getMessage());
		}
		m.addAttribute("entity", ac);
		return "/alarm/editAlarmConfig";

	}

	@ResponseBody
	@RequestMapping(value = "/delete")
	public JsonMessage delete(HttpServletRequest request, Model model,
							  @RequestParam(value = "entityId") long id) {

		try {
			this.alarmConfigService.deleteById(id);
			return jsonSuccess("记录已被成功刪除!");

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return jsonFail(ex.getMessage());
		}

	}

	@RequestMapping("/viewConfig.action")
	public ModelAndView viewConfig(Model model,
							 @RequestParam(value = "entityId", defaultValue="0") long id) {

		ModelAndView m = new ModelAndView();
		m.setViewName("/alarm/editAlarmConfig");
		try {
			if (id > 0) {
				AlarmConfig t = this.alarmConfigService.load(id);
				if (t == null) {

					m.addObject("entity", new AlarmConfig());
				} else
					m.addObject("entity", t);
			} else {
				m.addObject("entity", new AlarmConfig());
			}

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			m.addObject("发生错误:" + ex.getMessage());
		}

		return m;


	}

	/**
	 * 获取某一类型的基础数据 用于前台生成下拉框列表
	 */
	@RequestMapping("/terminalAlarmTypeList.action")
	@ResponseBody
	public JsonMessage getTerminalAlarmTypeList() {
		try {
			String hql = "from AlarmConfig where (alarmSource = ? or alarmSource = ?) and enabled = ? order by alarmSource, alarmType";
			List<AlarmConfig> alarmConfigs = this.alarmConfigService.query(hql, new Object[]{AlarmRecord.ALARM_FROM_TERM,AlarmRecord.ALARM_FROM_VIDEO, true});
			List<HashMap<String, Object>>  results = new ArrayList<>();
			HashMap<String, Object> t = new HashMap<>();
			t.put("id", "0");
			t.put("text", "终端报警");
			List<HashMap<String, Object>>  children = new ArrayList<>();
			t.put("children", children);
			for(AlarmConfig a : alarmConfigs)
			{
				if(StringUtils.isNumeric(a.getAlarmType())) {
					HashMap<String, Object> m = new HashMap<>();
					m.put("id", "" + a.getAlarmType());
					m.put("text", a.getName());
					children.add(m);
				}
			}
			results.add(t);

			return json(true, results);
		} catch (Exception ex) {
			super.log.error(ex.getMessage());
			super.log.error(ex.getStackTrace());
			return json(false, ex.getMessage());
		}
	}
}
